import { createSlice } from '@reduxjs/toolkit'
import { request } from '../../utils'
import { setToken as _setToken, getToken, clearToken } from '@/utils'

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || ''
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        clearUserInfo(state) {
            state.token = ''
            clearToken()
        }
    }
})

// 解构出actionCreater
const { setToken, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await request({
            url: '/user/login',
            method: 'POST',
            params: {
                username: loginForm.username,
                password: loginForm.password,
                captcha: loginForm.captcha
            }
        })
        
        // 根据后端API文档，检查响应格式
        if (res.code === 200) {
            // 登录成功，设置token和userId
            const token = res.data?.authorization || res.data?.token || res.data;
            const userId = res.data?.userId;
            
            dispatch(setToken(token))
            
            // 存储userId到localStorage并获取用户名
            if (userId) {
                localStorage.setItem('userId', userId);
                // 立即调用 getUserName 来获取并存储用户名
                await dispatch(getUserName(userId));
            }
        } else {
            // 登录失败，抛出错误
            if (res.msg && res.msg.includes('验证码')) {
                throw new Error('Captcha error.');
            } else {
                throw new Error(res.msg || '登录失败');
            }
        }
    }
}

// 获取并存储用户名的异步方法
const getUserName = (userId) => {
    return async (dispatch) => {
        if (!userId) {
            console.error("getUserName: userId is not provided.");
            return;
        }
        try {
            const res = await request({
                url: '/user/getUsernameByUserId',
                method: 'GET',
                params: { userId }
            });
            console.log(res)
            if (res && res.data) {
                localStorage.setItem('username', res.data);
            } else {
                localStorage.setItem('username', 'Anonymous');
            }
        } catch (error) {
            console.error("Failed to fetch username:", error);
            localStorage.setItem('username', 'Anonymous');
        }
    }
}

export { setToken, fetchLogin, clearUserInfo, getUserName }
export default userReducer